package cn.cxion.chat.app.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ToastUtils;
import com.lqr.optionitemview.OptionItemView;
import com.lxj.xpopup.XPopup;
import com.zhy.android.percent.support.PercentLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.cxion.chat.R;
import cn.cxion.chat.app.activity.ConstantActivity;
import cn.cxion.chat.app.bean.AppointmentInfo;
import cn.cxion.chat.app.bean.AppointmentTimes;
import cn.cxion.chat.app.bean.CheckContractBean;
import cn.cxion.chat.app.bean.CheckContractDetail;
import cn.cxion.chat.app.bean.CheckProcessDetail;
import cn.cxion.chat.app.bean.MessageAction;
import cn.cxion.chat.app.bean.MessageEvent;
import cn.cxion.chat.app.bean.OnHandInfo;
import cn.cxion.chat.app.bean.OptionBean;
import cn.cxion.chat.app.constant.Constant;
import cn.cxion.chat.app.util.CheckUtil;
import cn.cxion.chat.app.util.IflyUtil;
import cn.cxion.chat.app.util.LogUtil;
import cn.cxion.chat.app.util.StringUtil;
import cn.cxion.chat.app.util.UiHelp;
import cn.cxion.chat.app.view.popupview.AppointmentTimePopupView;
import cn.cxion.chat.app.view.popupview.DatePickPopupView;
import cn.cxion.chat.app.view.popupview.OptionListPopupView;
import cn.cxion.chat.kit.utils.FileUtils;

import static com.lxj.xpopup.enums.PopupAnimation.TranslateFromBottom;

public class AddScheduleView {

    private View view;
    private Activity activity;
    private int classType;
    private ViewHolder holder;
    private String path;
    private String fileNmae;
    private AppointmentInfo appointmentInfo;
    private DatePickPopupView.DateSelectListener listener;
    private int beginClick = 1;
    private int finishClick = 2;

    private boolean isNew=true;

    //日程开始时间
    private AppointmentTimes beginTime;
    //日程结束时间
    private AppointmentTimes finishTime;
    //重复
    private OptionBean repeat;
    //标签
    private OptionBean tag;


    public AddScheduleView(Context context, int classType) {
        view = LayoutInflater.from(context).inflate(R.layout.view_checkcontract, null);
        activity = (Activity) context;
        this.classType = classType;
        init();
    }

    public AddScheduleView(Context context, int classType, AppointmentInfo appointmentInfo) {
        view = LayoutInflater.from(context).inflate(R.layout.view_checkcontract, null);
        activity = (Activity) context;
        this.classType = classType;
        this.appointmentInfo = appointmentInfo;
        init();
    }

    public View getView() {
        return view;
    }

    private void init() {

        EventBus.getDefault().register(this);
        holder = new ViewHolder(activity, view);
        viewControl();
        holder.accessory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtil.isEmpty(path))
                    activity.startActivity(FileUtils.getViewIntent(activity, new File(path)));
            }
        });
        //配置数据
        if (appointmentInfo != null) {
            isNew=false;
            holder.etSuggest.setText(appointmentInfo.getContent());
            holder.switchWholeday.setChecked(appointmentInfo.isWholeDay());
            if(appointmentInfo.getBeginTime()!=null&&appointmentInfo.getBeginTime().getTimeText()!=null){
                holder.begin.setRightText(appointmentInfo.getBeginTime().getTimeText());
                beginTime=appointmentInfo.getBeginTime();
            }
            if(appointmentInfo.getFinishTime()!=null&&appointmentInfo.getFinishTime().getTimeText()!=null){
                holder.finish.setRightText(appointmentInfo.getFinishTime().getTimeText());
                finishTime=appointmentInfo.getFinishTime();
            }
            if(appointmentInfo.getRepeat()!=null&&appointmentInfo.getRepeat().getName()!=null){
                holder.repeat.setRightText(appointmentInfo.getRepeat().getName());
                repeat=appointmentInfo.getRepeat();
            }
            if(appointmentInfo.getTag()!=null&&appointmentInfo.getTag().getName()!=null){
                holder.tag.setRightText(appointmentInfo.getTag().getName());
                tag=appointmentInfo.getTag();
            }
        }
        if (appointmentInfo == null) {
            appointmentInfo = new AppointmentInfo();
        }
    }

    private void viewControl() {
        switch (classType) {
            case Constant.ADDSCHEDULE:
                holder.llCheckcontract.setVisibility(View.GONE);
                holder.llSchedule.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    //保存按钮
    public void rightClick() {
        if (classType == Constant.ADDSCHEDULE) {
            save();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(MessageEvent messageEvent) {

    }

    private void save() {
        if (!CheckUtil.checkEditText(activity, "详情不能为空！", holder.etSuggest))
            return;
        if(!isNew){
            getBean();
        }
        appointmentInfo.setBeginTime(beginTime);
        appointmentInfo.setFinishTime(finishTime);
        appointmentInfo.setRepeat(repeat);
        appointmentInfo.setTag(tag);
        appointmentInfo.setContent(holder.etSuggest.getText().toString());
        appointmentInfo.setWholeDay(holder.switchWholeday.isChecked());
        if(!isNew){
            ToastUtils.showShort("修改成功");
        }else{
            appointmentInfo.setUuid(StringUtil.getUUID());
            Constant.getScheduleBeanList().add(appointmentInfo);
            ToastUtils.showShort("添加成功");
        }
        EventBus.getDefault().post(new MessageEvent(MessageAction.ReSchedule,""));
        activity.finish();
    }

    public void getBean() {
        for (AppointmentInfo bean : Constant.getScheduleBeanList()) {
            if (bean.getUuid().equals(appointmentInfo.getUuid())) {
                appointmentInfo = bean;
            }
        }
    }

    public void unregister() {
        EventBus.getDefault().unregister(this);
    }

    private void showDate(int type) {
        AppointmentTimes appointmentTimes=null;
        if(type==beginClick){
           appointmentTimes=appointmentInfo.getBeginTime();
        }else{
            appointmentTimes=appointmentInfo.getFinishTime();
        }
        DatePickPopupView datePickPopupView = new DatePickPopupView(activity, appointmentTimes);
        datePickPopupView.setOnDateSelectListener(new DatePickPopupView.DateSelectListener() {
            @Override
            public void selectDate(AppointmentTimes appointmentTimes) {
                if (type == beginClick) {
                    beginTime=appointmentTimes;
                    holder.begin.setRightText(appointmentTimes.getTimeText());
                } else {
                    finishTime=appointmentTimes;
                    holder.finish.setRightText(appointmentTimes.getTimeText());
                }
            }
        });
        new XPopup.Builder(activity)
                .popupAnimation(TranslateFromBottom)
                .asCustom(datePickPopupView/*.enableDrag(false)*/)
                .show();
    }
    private void showRepeatList() {
        OptionListPopupView.showView(activity, Constant.getAddScheduleRepeatList(), new OptionListPopupView.OnOptionSelectListener() {
            @Override
            public void ok(OptionBean optionBean) {
                repeat=optionBean;
                holder.repeat.setRightText(optionBean.getName());
            }
        });
    } private void showTagList() {
        OptionListPopupView.showView(activity, Constant.getAddScheduleTagList(), new OptionListPopupView.OnOptionSelectListener() {
            @Override
            public void ok(OptionBean optionBean) {
                tag=optionBean;
                holder.tag.setRightText(optionBean.getName());
            }
        });
    }

    class ViewHolder {

        @Bind(R.id.et_suggest)
        AutoCompleteTextView etSuggest;
        @Bind(R.id.img_recognize)
        ImageView imgRecognize;
        @Bind(R.id.accessory)
        OptionItemView accessory;
        @Bind(R.id.ll_accessory)
        RelativeLayout llAccessory;
        @Bind(R.id.img_accessory)
        ImageView imgAccessory;
        @Bind(R.id.recipients)
        OptionItemView recipients;
        @Bind(R.id.copyto)
        OptionItemView copyto;
        @Bind(R.id.exigency)
        OptionItemView exigency;
        @Bind(R.id.swith_exigency)
        Switch swichtEigency;
        @Bind(R.id.ll_exigency)
        LinearLayout llExigency;
        @Bind(R.id.ll_accessory_new)
        RelativeLayout llAccessoryNew;
        @Bind(R.id.history)
        OptionItemView history;
        @Bind(R.id.showstatus)
        OptionItemView showstatus;
        @Bind(R.id.status_stocks)
        RadioButton statusStocks;
        @Bind(R.id.status_inhand)
        RadioButton statusInhand;
        @Bind(R.id.status_untreade)
        RadioButton statusUntreade;
        @Bind(R.id.rg_status)
        RadioGroup rgStatus;
        @Bind(R.id.ll_checkcontract)
        PercentLinearLayout llCheckcontract;
        @Bind(R.id.switch_wholeday)
        Switch switchWholeday;
        @Bind(R.id.ll_wholeday)
        LinearLayout llWholeday;
        @Bind(R.id.begin)
        OptionItemView begin;
        @Bind(R.id.finish)
        OptionItemView finish;
        @Bind(R.id.repeat)
        OptionItemView repeat;
        @Bind(R.id.tag)
        OptionItemView tag;
        @Bind(R.id.invitee)
        OptionItemView invitee;
        @Bind(R.id.ll_schedule)
        PercentLinearLayout llSchedule;
        @Bind(R.id.appointmentlawyer)
        OptionItemView appointmentlawyer;
        @Bind(R.id.appointmenttime)
        OptionItemView appointmenttime;
        @Bind(R.id.place)
        OptionItemView place;
        @Bind(R.id.ll_appointmentlawyer)
        PercentLinearLayout llAppointmentlawyer;
        Context context;

        ViewHolder(Context context, View view) {
            ButterKnife.bind(this, view);
            this.context = context;
        }

        boolean clickAble = true;


        @OnClick({R.id.et_suggest, R.id.img_recognize, R.id.recipients, R.id.copyto, R.id.exigency, R.id.ll_exigency, R.id.history, R.id.showstatus, R.id.status_stocks, R.id.status_inhand, R.id.status_untreade, R.id.ll_checkcontract, R.id.ll_wholeday, R.id.begin, R.id.finish, R.id.repeat, R.id.tag, R.id.invitee, R.id.ll_schedule, R.id.appointmentlawyer, R.id.appointmenttime, R.id.place, R.id.ll_appointmentlawyer, R.id.img_accessory})
        public void onViewClicked(View view) {
            if (!clickAble)
                return;
            switch (view.getId()) {
                case R.id.et_suggest:
                    break;
                case R.id.img_recognize:
                    IflyUtil iflyUtil = new IflyUtil();
                    iflyUtil.recognize(context, etSuggest);
                    break;
                case R.id.recipients:
                    break;
                case R.id.copyto:
                    break;
                case R.id.exigency:
                    clickExigency();
                    break;
                case R.id.ll_exigency:
                    clickExigency();
                    break;
                case R.id.history:
                    break;
                case R.id.showstatus:
                    break;
                case R.id.status_stocks:
                    break;
                case R.id.status_inhand:
                    break;
                case R.id.status_untreade:
                    break;
                case R.id.ll_checkcontract:
                    break;
                case R.id.ll_wholeday:
                    clickWholeday();
                    break;
                case R.id.begin:
                    UiHelp.hideKeyboard(begin);
                    showDate(beginClick);
                    break;
                case R.id.finish:
                    showDate(finishClick);
                    break;
                case R.id.repeat:
                    showRepeatList();
                    break;
                case R.id.tag:
                    showTagList();
                    break;
                case R.id.invitee:
                    ConstantActivity.show(activity,Constant.INVITEE);
                    break;
                case R.id.ll_schedule:
                    break;
                case R.id.appointmentlawyer:
                    break;
                case R.id.appointmenttime:
                    break;
                case R.id.place:
                    break;
                case R.id.ll_appointmentlawyer:
                    break;
                case R.id.img_accessory:
                    clickFile();
                    break;
            }
        }

        public void setClickAble(boolean clickAble) {
            this.clickAble = clickAble;
        }


        //紧急按钮
        private void clickExigency() {
            if (swichtEigency.isChecked()) {
                swichtEigency.setChecked(false);
            } else {
                swichtEigency.setChecked(true);
            }
        }

        //全天按钮
        private void clickWholeday() {
            if (switchWholeday.isChecked()) {
                switchWholeday.setChecked(false);
            } else {
                switchWholeday.setChecked(true);
            }
        }

        private void clickFile() {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//无类型限制
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            ((Activity) context).startActivityForResult(intent, 100);
        }
    }

}
